import configureStore from 'redux-mock-store'

import errorMiddleware from 'middlewares/errorMiddleware'
import { errorAlert } from 'modules/system'

const middlewares = [errorMiddleware]
let mockStore
let store

beforeEach(() => {
  mockStore = configureStore(middlewares)
  store = mockStore({})
})

it('should call next if there is no error', () => {
  const action = {
    type: 'FETCH_LIST',
    error: false,
  }

  store.dispatch(action)

  expect(store.getActions()).toEqual([action])
})

it('should call next if there is error', () => {
  const status = 413
  const statusText = 'File is too large'
  const action = {
    type: 'FETCH_LIST',
    error: true,
    payload: {
      status,
      statusText,
    },
  }
  const errorMessage = `${status} ${statusText}`

  store.dispatch(action)

  expect(store.getActions()[0]).toMatchObject(errorAlert(errorMessage))
})

it('should call next if there is error without status', () => {
  const payload = 'File is too large'
  const action = {
    type: 'FETCH_LIST',
    error: true,
    payload,
  }
  const errorMessage = payload

  store.dispatch(action)

  expect(store.getActions()[0]).toMatchObject(errorAlert(errorMessage))
})

it('should call next if there is error with custom error messages', () => {
  const status = 403
  const statusText = 'File is too large'
  const errorMessage = 'Fucking large'
  const action = {
    type: 'FETCH_LIST',
    error: true,
    payload: {
      status,
      statusText,
    },
    meta: {
      errors: {
        [status]: errorMessage,
      },
    },
  }

  store.dispatch(action)

  expect(store.getActions()[0]).toMatchObject(errorAlert(errorMessage))
})

it('should call `formatErrorMessage` in order to format error message if passing it', () => {
  const originalErrorMessage = 'File is too large'
  const payload = {
    formatErrorMessage: () => originalErrorMessage,
  }
  const action = {
    type: 'FETCH_LIST',
    error: true,
    payload,
  }

  store.dispatch(action)

  expect(store.getActions()[0]).toMatchObject(errorAlert(originalErrorMessage))
})

it('suppressError', () => {
  const action = {
    type: 'FETCH_LIST',
    meta: { suppressError: true },
    payload: {},
    error: true,
  }

  store.dispatch(action)

  expect(store.getActions().length === 1).toBe(true)
})

it('should dispatch ERROR_MODAL_SHOW action when setting `errorTrigger` as MODAL', () => {
  const action = {
    type: 'FETCH_LIST',
    meta: { errorTrigger: 'MODAL' },
    payload: {},
    error: true,
  }

  store.dispatch(action)

  const actions = store.getActions()

  expect(actions.length === 2).toBe(true)
  expect(actions[0].type === 'ERROR_MODAL_SHOW').toBe(true)
  expect(actions).toMatchSnapshot()
})
